﻿#include "MaskWidget.h"

MaskWidget* MaskWidget::instance()
{
	static MaskWidget* instance;
	if (!instance)
	{
		instance = new MaskWidget;
	}

	return instance;
}
MaskWidget::MaskWidget(QWidget* parent)
	:QWidget(parent, Qt::FramelessWindowHint | Qt::WindowDoesNotAcceptFocus)
{
	this->setStyleSheet("background-color:rgba(193,193,201,180)");
	this->setAttribute(Qt::WA_StyledBackground);								//设置背景跟随样式变化
}

void MaskWidget::setMainWidget(QWidget* widget)
{
	if (!widget)
	{
		qWarning() << "the widget is nullptr";
		return;
	}
	if (m_mainwidget)
	{
		qWarning() << "the mainwidget is exsist";
	}


	m_mainwidget = widget;


	this->setParent(m_mainwidget);
	this->hide();							//默认隐藏
	m_mainwidget->installEventFilter(this);
}

void MaskWidget::addDialog(QWidget* dialog)
{
	if (!dialog)
	{
		qWarning() << "dialog is nullptr";
		return;
	}

	//如果该对话框已经存放到set容器中：
	auto find_dialog = m_dialogs.find(dialog);
	if (find_dialog != m_dialogs.end())
	{
		qWarning() << "the dialog is exists ";
		return;
	}

	//存放：
	m_dialogs.insert(dialog);
	//添加事件过滤器：
	dialog->installEventFilter(this);

}

void MaskWidget::popup(QWidget* dialog)
{
	//添加到set容器里：
	addDialog(dialog);


	if (dialog && m_dialogs.contains(dialog))
	{
		this->show();
		dialog->show();
		//把焦点设置给弹出的对话框：方便实现按键控制对话框
		dialog->setFocus();
	}
}

void MaskWidget::closeWidget()
{
	this->close();
}

bool MaskWidget::eventFilter(QObject* object, QEvent* ev)
{
	//当前是不是MainWidget对象：
	if (object == m_mainwidget)
	{
		if (ev->type() == QEvent::Resize)			//蒙层的大小随窗口的大小而改变
		{
			this->setGeometry(m_mainwidget->rect());
		}
	}
	else
	{
		if (ev->type() == QEvent::Hide)									//弹出的对话框隐藏了，那么蒙层也随之隐藏；
		{
			this->hide();
		}
		else if (ev->type() == QEvent::KeyRelease)						//如果是键盘按下
		{
			auto keyev = dynamic_cast<QKeyEvent*>(ev);		//下行转换
			if (keyev->key() == Qt::Key_Escape)							//如果是esc按键按下
			{
				this->hide();
			}
		}
	}



	return false;
}
